<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="发起时间" prop="useTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_commit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['humanresource:mobility:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['humanresource:mobility:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['humanresource:mobility:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['humanresource:mobility:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="mobilityList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="发起人" align="center" prop="initialId" fixed="left">
          <template #default="scope">
            <span>{{ scope.row.initialName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptId" fixed="left">
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发起时间" align="center" prop="initialTime" width="120" fixed="left">
          <template #default="scope">
            <span>{{ parseTime(scope.row.initialTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="部门" align="center" prop="deptId" >
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="项目" align="center" prop="projectName" >
          <template #default="scope">
            <el-tooltip :content="scope.row.projectName" placement="top" :disabled="!scope.row.projectName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.projectName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="入职时间" align="center" prop="onboardTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.onboardTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="员工类别" align="center" prop="employeeType">
          <template #default="scope">
            <dict-tag :options="employee_type" :value="scope.row.employeeType"/>
          </template>
        </el-table-column>
        <el-table-column label="申请离职时间" align="center" prop="applyResignTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyResignTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后工作日时间" align="center" prop="lastWorkTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.lastWorkTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="离职类型" align="center" prop="resignType" width="120">
          <template #default="scope">
            <dict-tag :options="employee_resign_type" :value="scope.row.resignType"/>
          </template>
        </el-table-column>
        <el-table-column label="离职原因" align="center" prop="resignReason" />
        <el-table-column label="离职建议" align="center" prop="resignSuggestion" >
          <template #default="scope">
            <el-tooltip :content="scope.row.resignSuggestion" placement="top" :disabled="!scope.row.resignSuggestion">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.resignSuggestion }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="所属部门交接事宜" align="center" prop="deptHandover" width="130">
          <template #default="scope">
            <el-tooltip :content="scope.row.deptHandover" placement="top" :disabled="!scope.row.deptHandover">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.deptHandover }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="综合办交接事宜" prop="generalOfficeHandovers" width="130">
          <template #default="scope">
            <el-tooltip :content="scope.row.generalOfficeHandovers?.join('、')" placement="top" :disabled="!scope.row.generalOfficeHandovers?.length">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.generalOfficeHandovers?.join("、") || '-' }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="财务中心交接事宜" align="center" prop="financialCenterHandover" width="130">
          <template #default="scope">
            <el-tooltip :content="scope.row.financialCenterHandover" placement="top" :disabled="!scope.row.financialCenterHandover">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.financialCenterHandover }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="离职证明" align="center" prop="resignProve">
          <template #default="scope">
            <dict-tag :options="resign_prove_type" :value="scope.row.resignProve"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="120" fixed="right">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status" fixed="right">
          <template #default="scope">
            <dict-tag :options="approval_commit_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="110">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['humanresource:mobility:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['humanresource:mobility:remove']"></el-button>
            </el-tooltip>
            <!-- 审批按钮 -->
            <el-tooltip content="提交审批" placement="top">
              <el-button
                link
                type="primary"
                icon="DocumentChecked"
                @click="openApprovalFlow(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改员工离职申请审批对话框 -->
    <el-dialog 
      :title="dialog.title" 
      v-model="dialog.visible" 
      width="900px" 
      append-to-body
      @opened="handleDialogOpen"
      class="seal-dialog"
    >
      <template #default>
        <el-form ref="mobilityFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="发起人" prop="initialName">
                <el-input v-model="form.initialName" placeholder="请输入发起人名称" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发起部门" prop="initialDeptId">
                  <el-tree-select
                    v-model="form.initialDeptId"
                    :data="deptTree"
                    placeholder="请选择发起部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                  />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发起时间" prop="initialTime">
                <el-date-picker clearable
                  v-model="form.initialTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择发起时间"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="离职部门" prop="deptId">
                  <el-tree-select
                    v-model="form.deptId"
                    :data="deptTree"
                    placeholder="请选择离职部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                    @change="handleDeptChange"
                  />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职时间" prop="onboardTime">
                <el-date-picker clearable
                  v-model="form.onboardTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择入职时间"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="离职项目" prop="projectIdArray">
                <el-select
                  v-model="form.projectIdArray"
                  multiple
                  placeholder="请输入项目名称搜索"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="searchProjects"
                  :loading="projectLoading"
                  style="width: 100%"
                  @change="handleProjectChange"
                >
                  <el-option
                    v-for="project in projectList"
                    :key="project.id"
                    :label="`${project.proName} (${project.proNumber || ''})`"
                    :value="String(project.id)"
                  />
                  <template #empty>
                    <div class="text-center p-2">
                      <span v-if="projectLoading">加载中...</span>
                      <span v-else-if="projectSearchKeyword && projectList.length === 0">未找到相关项目</span>
                      <span v-else>请输入项目名称进行搜索</span>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="员工类别" prop="employeeType">
                <el-select v-model="form.employeeType" placeholder="请选择员工类别">
                  <el-option
                      v-for="dict in employee_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请离职时间" prop="applyResignTime">
                <el-date-picker clearable
                  v-model="form.applyResignTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择申请离职时间"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最后工作日时间" prop="lastWorkTime">
                <el-date-picker clearable
                  v-model="form.lastWorkTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择最后工作日时间"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="离职类型" prop="resignType">
                <el-select v-model="form.resignType" placeholder="请选择离职类型">
                  <el-option
                      v-for="dict in employee_resign_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="离职原因" prop="resignReason">
                <el-input v-model="form.resignReason" placeholder="请输入离职原因" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="离职建议" prop="resignSuggestion">
                <el-input v-model="form.resignSuggestion" placeholder="请输入离职建议" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所属部门交接事宜" prop="deptHandover">
                <el-input v-model="form.deptHandover" placeholder="请输入所属部门交接事宜" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
            <el-col :span="24"> 
              <el-form-item label="综合办交接事宜" prop="generalOfficeHandovers">
                <el-select
                  v-model="form.generalOfficeHandovers"
                  placeholder="请选择综合办交接事宜"
                  style="width: 100%;"
                  multiple
                  clearable
                >
                  <el-option label="饭卡" value="饭卡" />
                  <el-option label="门禁系统" value="门禁系统" />
                  <el-option label="电脑设备" value="电脑设备" />
                  <el-option label="系统权限" value="系统权限" />
                  <el-option label="公车交还" value="公车交还" />
                  <el-option label="公车违章处理" value="公车违章处理" />
                  <el-option label="住宿" value="住宿" />
                  <el-option label="社保公积金" value="社保公积金" />
                  <el-option label="考勤" value="考勤" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24"> 
              <el-form-item label="财务中心交接事宜" prop="financialCenterHandover">
                <el-select
                  v-model="form.financialCenterHandover"
                  placeholder="请选择录用类型"
                  @change="handleTypeChange"
                  filterable
                  style="width: 100%;"
                >
                  <el-option label="无" value="无" />
                  <el-option label="有" value="有" />
                </el-select>
                <el-dialog
                  title="请输入其他增补类型"
                  :model-value="showOtherDialog"
                  @update:model-value="val => showOtherDialog = val"
                  width="400px"
                  :close-on-click-modal="false"
                  custom-class="other-dialog"
                  center
                >
                  <div class="dialog-content">
                    <el-input
                      v-model="tempOtherType"
                      placeholder="请输入其他类型"
                      clearable
                      style="width: 100%;"
                      @keyup.enter="confirmOther"
                    />
                  </div>
                  <template #footer>
                    <div class="dialog-footer-center">
                      <el-button @click="cancelOther">取消</el-button>
                      <el-button type="primary" @click="confirmOther">确认</el-button>
                    </div>
                  </template>
                </el-dialog>
              </el-form-item>            
            </el-col>
            <el-col :span="24"> 
              <el-form-item label="离职证明" prop="resignProve">
                <el-select v-model="form.resignProve" placeholder="请选择离职证明">
                  <el-option
                      v-for="dict in resign_prove_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>            
            </el-col>
            <el-col :span="24"> 
              <el-form-item label="附件上传" prop="attachmentId">
                <el-input v-model="form.attachmentName" placeholder="请点击附件上传" @click="handleAttachmentUpload(11)" type="textarea" :rows="3"/>
              </el-form-item>        
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上传对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        v-model:file-list="uploadRefFileList"
        accept=".doc,.docx,.pdf,.jpg,.png,.jpeg,.gif,.xlsx,.xls,.ppt,.pptx"
        :headers="upload.headers"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" 
        :on-remove="handleFileRemove"
        :auto-upload="false"
        :multiple="true"
        drag
        list-type="picture"
      >
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>

      <!-- 文件列表 -->
      <div v-if="uploadRefFileList.length > 0" class="mt-4">
        <el-table :data="uploadRefFileList" size="small" border>
          <el-table-column prop="name" label="文件名" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button link type="primary" @click="handlePreview(scope.row)">预览</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer> 
        <div class="dialog-footer"> 
          <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">确 定</el-button> 
          <el-button @click="cancelUpload">取 消</el-button> 
        </div> 
      </template>
    </el-dialog>

    <!-- 文件预览组件 -->
    <FilePreview v-model="preview.open"
                :url="preview.url"
                :title="preview.title"
                :type="preview.type" />

    <!-- 审核流程配置对话框 --> 
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="'HR-ONBOARD-RESIGN-AUDIT'"
      :business-id="auditIdForApproval" :key="auditIdForApproval" title="配置员工离职申请审核流程" @confirm="handleApprovalConfirm"
      @cancel="handleApprovalCancel" />
  </div>
</template>

<script setup name="Mobility" lang="ts">
import { listMobility, getMobility, delMobility, addMobility, updateMobility } from '@/api/general/humanresources/mobility/resign/index';
import { MobilityVO, MobilityQuery, MobilityForm } from '@/api/general/humanresources/mobility/resign/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import { ItemTreeNode } from '@/api/project/init/contract/types';
import { listProContract } from '@/api/project/init/contract';
import { pageListProInfo } from '@/api/project/init/proInfo';
import { globalHeaders } from '@/utils/request';
import { UploadQuery } from '@/api/general/administration/car/upload/types';
import { uploadAttachment, deleteUploadFile, queryAllByUser } from '@/api/general/administration/car/apply';
import dayjs from "dayjs";
import { resetApprovalStatus } from '@/components/ApprovalFlow/api';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import { pageListForQuery, getProInfo } from '@/api/project/init/proInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { employee_type, employee_resign_type, resign_prove_type  } = toRefs<any>(proxy?.useDict('employee_type', 'employee_resign_type', 'resign_prove_type'));

const BASE_URL = import.meta.env.VITE_APP_BASE_API || 'http://localhost:8080';
const mobilityList = ref<MobilityVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const mobilityFormRef = ref<ElFormInstance>();
// 用户信息
const userStore = useUserStore();

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 初始化项目下拉框
const projectTree = ref<ItemTreeNode[]>([]);

// 引入数据字典
const { adm_item_type, approval_commit_status } = toRefs<any>(proxy?.useDict('adm_item_type', 'approval_commit_status'));

// 是否选择“其他”类型
const otherType = ref('')      // 用户手输的“其他”类型
const isOther = ref(false)     // 是否选择“其他”
const showOtherDialog = ref(false); // 控制弹窗显示
const tempOtherType = ref("");       // 弹窗临时输入

// 导入相关
const uploadRef = ref<any>();
// 已上传文件，用于回显和 form.attachment
const uploadedFiles = ref<any[]>([]);
// 当前待上传文件列表
const uploadRefFileList = ref<any[]>([]);
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 上传的类型
  type: undefined,
  // 设置上传的请求头部
  headers: globalHeaders()
});

// 预览状态
const preview = reactive({
  open: false,
  url: "",
  title: "",
  type: "",
  rawFile: null
})

// 搜索关键词
const projectSearchKeyword = ref('');
const flowSearchKeyword = ref('');
const projectLoading = ref(false);
const projectList = ref<ProInfoVO[]>([]);
// 防抖计时器
let projectSearchTimer: NodeJS.Timeout | null = null;
// 防止并发请求覆盖
let currentRequestId = 0;

// 定义需要触发必填校验的部门名称或 ID
const requiredProjectDepts = ["董办", "综合办", "财务中心","商务中心"];
// 回显状态，防止重复调用
const backfillDone = ref(false);

// 提交审核相关
const approvalFlowVisible = ref(false);
const currentSubmitAuditRow = ref<any>(null);
const auditIdForApproval = ref<string | number | undefined>(undefined);

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: MobilityForm = {
  id: undefined,
  initialId: userStore.userId,
  initialName: userStore.name,
  initialDeptId: userStore.deptId,
  initialDeptName: userStore.deptName,
  initialTime: formatLocalDate(),
  number: undefined,
  name: undefined,
  deptId: undefined,
  deptName: undefined,
  projectIdArray: [] as string[],
  projectId: undefined,
  projectName: undefined,
  onboardTime: undefined,
  employeeType: undefined,
  applyResignTime: undefined,
  lastWorkTime: undefined,
  resignType: undefined,
  resignReason: undefined,
  resignSuggestion: undefined,
  deptHandover: undefined,
  generalOfficeHandover: undefined,
  generalOfficeHandovers: [],
  financialCenterHandover: undefined,
  resignProve: undefined,
  attachmentId: undefined,
  attachmentName: undefined,
  status: undefined,
}
const data = reactive<PageData<MobilityForm, MobilityQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    initialId: undefined,
    initialDeptId: undefined,
    initialTime: undefined,
    number: undefined,
    name: undefined,
    deptId: undefined,
    projectId: undefined,
    onboardTime: undefined,
    employeeType: undefined,
    applyResignTime: undefined,
    lastWorkTime: undefined,
    resignType: undefined,
    resignReason: undefined,
    resignSuggestion: undefined,
    deptHandover: undefined,
    generalOfficeHandover: undefined,
    financialCenterHandover: undefined,
    resignProve: undefined,
    attachmentId: undefined,
    status: undefined,
    createTime: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
     initialName: [
    { required: true, message: "发起人不能为空", trigger: "change" }
    ],
    initialDeptId: [
      { required: true, message: "发起部门不能为空", trigger: "change" }
    ],
    initialTime: [
      { required: true, message: "发起时间不能为空", trigger: "change" },
      {
        validator: (_: any, value: string, callback: Function) => {
          if (!value) return callback();
          const today = dayjs().startOf("day");
          const initTime = dayjs(value).startOf("day");
          if (initTime.isAfter(today)) {
            return callback(new Error("发起时间不能晚于今天"));
          }
          callback();
        },
        trigger: "change"
      }
    ],
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "部门不能为空", trigger: "change" }
    ],
    projectId: [
      {
        validator: (_: any, value: any, callback: Function) => {
          if (form.value.deptId && !value) {
            return callback(new Error("原项目必填"));
          }
          callback();
        },
        trigger: "change"
      }
    ],
    onboardTime: [
      { required: true, message: "入职时间不能为空", trigger: "change" },
      {
        validator: (_: any, value: string, callback: Function) => {
          if (!value) return callback();
          const today = dayjs().startOf("day");
          const onboard = dayjs(value).startOf("day");
          if (onboard.isSame(today) || onboard.isAfter(today)) {
            return callback(new Error("入职时间必须小于当天"));
          }
          callback();
        },
        trigger: "change"
      }
    ],
    employeeType: [
      { required: true, message: "员工类别不能为空", trigger: "change" }
    ],
    applyResignTime: [
      { required: true, message: "申请离职时间不能为空", trigger: "change" }
    ],
    lastWorkTime: [
      { required: true, message: "最后工作日不能为空", trigger: "change" },
      {
        validator: (_: any, value: string, callback: Function) => {
          if (!value) return callback();
          if (form.value.applyResignTime && dayjs(value).isBefore(dayjs(form.value.applyResignTime))) {
            return callback(new Error("最后工作日不能早于申请离职时间"));
          }
          callback();
        },
        trigger: "change"
      }
    ],
    resignType: [
      { required: true, message: "离职类型不能为空", trigger: "change" }
    ],
    resignReason: [
      { required: true, message: "离职原因不能为空", trigger: "blur" }
    ],
    resignSuggestion: [
      { required: true, message: "离职建议不能为空", trigger: "blur" }
    ],
    deptHandover: [
      { required: true, message: "所属部门交接事宜不能为空", trigger: "blur" }
    ],
    generalOfficeHandovers: [
      {
        type: "array",
        required: true,
        message: "综合办交接事宜不能为空",
        trigger: "change"
      }
    ],
    financialCenterHandover: [
      { required: true, message: "财务中心交接事宜不能为空", trigger: "change" }
    ],
    resignProve: [
      { required: true, message: "离职证明不能为空", trigger: "change" }
    ],
    attachmentId: [
      { required: true, message: "附件上传不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询员工离职申请审批列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listMobility(params);
    // 解析综合办交接事宜
    mobilityList.value = res.rows.map((item: any) => {
      if (item.generalOfficeHandover) {
        try {
          item.generalOfficeHandovers = JSON.parse(item.generalOfficeHandover);
        } catch (e) {
          console.warn("generalOfficeHandover JSON解析失败", e);
          item.generalOfficeHandovers = [];
        }
      } else {
        item.generalOfficeHandovers = [];
      }
      return item;
    });
    total.value = res.total;
  } catch (error) {
    console.error("获取列表失败:", error);
    proxy?.$modal.msgError("获取列表失败");
  } finally {
    loading.value = false;
  }
};


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  mobilityFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: MobilityVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加员工离职申请审批";
  // 初始化 number
  const isNew = true;
  initOrAssignNumber(data.form, isNew);
}

/** 修改按钮操作 */
const handleUpdate = async (row?: MobilityVO) => {
  if (row.status != 4) {
    ElMessage.error("只能对审核不过的申请进行修改")
    return;
  }
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getMobility(_id);
  const data = { ...res.data };
  // generalOfficeHandover -> generalOfficeHandovers
  if (data.generalOfficeHandover) {
    try {
      data.generalOfficeHandovers = JSON.parse(data.generalOfficeHandover);
    } catch (e) {
      console.warn("generalOfficeHandover 字段解析失败", e);
      data.generalOfficeHandovers = [];
    }
  } else {
    data.generalOfficeHandovers = [];
  }
  // 将解析后的字段赋给表单
  Object.assign(form.value, data);
  // 初始化附件列表，但不要打开弹窗
  if (form.value.number && form.value.initialId) {
    await loadAttachments(); // 仅刷新上传组件列表，不操作 upload.open
  }
  dialog.visible = true;
  dialog.title = "修改员工离职申请审批";
};


/** 提交按钮 */
const submitForm = () => {
  mobilityFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const submitData = { ...form.value };
      if (Array.isArray(submitData.generalOfficeHandovers)) {
        submitData.generalOfficeHandover = JSON.stringify(submitData.generalOfficeHandovers);
      }
      buttonLoading.value = true;
      // 提交前处理 projectId
      form.value.projectId = form.value.projectIdArray?.join(',') || '';
      try {
        if (form.value.id) {
          await updateMobility(submitData);
          // 调用重置审核流程接口
          await resetApprovalStatus('HR-ONBOARD-RESIGN-AUDIT', Number(form.value.id), '不可审核')
        } else {
          const res = await addMobility(submitData);
          // 触发审核流程配置对话框
          auditIdForApproval.value = res.data;
          approvalFlowVisible.value = true;
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};


/** 删除按钮操作 */
const handleDelete = async (row?: MobilityVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除员工离职申请审批编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delMobility(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('humanresource/mobility/export', {
    ...queryParams.value
  }, `mobility_${new Date().getTime()}.xlsx`)
}

// 对话框打开时滚动到顶部
const handleDialogOpen = async () => {
  await nextTick(); // 确保 DOM 渲染完成
  // 使用 document.querySelector 精准获取 Teleport 后的 el-dialog__body
  const scrollBody = document.querySelector<HTMLElement>('.seal-dialog .el-dialog__body');
  if (scrollBody) {
    scrollBody.scrollTop = 0; // 滚动到顶部
  } else {
    console.warn('未找到 el-dialog__body');
  }
};

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 将最终选择值更新到 form.type
watch(otherType, (val) => {
  if (isOther.value) {
    form.value.financialCenterHandover = val
  }
})

// 选择变化处理
const handleTypeChange = (val) => {
  if (val === "有") {
    // 如果已经有值，弹窗显示当前值
    tempOtherType.value = otherType.value || "";
    showOtherDialog.value = true;
  } else {
    // 如果取消选择“其他”，清空手动输入值
    otherType.value = "";
  }
};

// 弹窗取消
const cancelOther = () => {
  showOtherDialog.value = false;
  form.value.financialCenterHandover = ""; // 取消“其他”，清空原下拉值
};

// 弹窗确认
const confirmOther = () => {
  otherType.value = tempOtherType.value;
  form.value.financialCenterHandover = otherType.value; // 显示在原下拉框
  showOtherDialog.value = false;
};

/**
 * 文件上传中处理
 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};


/**
 * 提交上传文件
 */
const submitFileForm = async () => {
  const files = uploadRefFileList.value.map(f => f.raw).filter(Boolean);
  if (!files.length) {
    ElMessage.warning("请先选择文件！");
    return;
  }

  upload.isUploading = true;
  try {
    await uploadAttachment(files, data.form.initialId, data.form.number, upload.type);

    // 上传成功后刷新附件列表
    await loadAttachments();

    // ⚠️ 触发回调，更新表单或者其他需要刷新逻辑
    // 例如：重新计算 attachmentId / attachmentName 已在 loadAttachments 里处理

    ElMessage.success("上传成功");

    // 清空临时待上传文件
    uploadRefFileList.value = [];
    uploadRef.value?.clearFiles();

    // 强制关闭上传弹窗，防止自动弹出
    upload.open = false;

  } catch (err) {
    console.error(err);
    ElMessage.error("上传失败，请重试");
  } finally {
    upload.isUploading = false;
  }
};



/**
 * 打开附件上传弹窗
 */
const handleAttachmentUpload = (type: number) => {
  upload.title = '附件信息上传';
  upload.type = type;
  upload.open = true; // 只有用户点击才打开
    // 加载附件列表数据，但不要重复打开弹窗
  loadAttachments(); // 只是刷新列表，不操作 upload.open
};

 // 页面初始化或表单加载完成后调用
const loadAttachments = async () => {
  if (!data.form.number || !data.form.initialId) return; // 新增表单未生成number或useId，不加载

  try {
    const query: UploadQuery = {
      number: data.form.number,
      uploadId: data.form.initialId
    };

    const response = await queryAllByUser(query);
    const existingFiles = response.data || [];

    uploadedFiles.value = existingFiles.map(f => ({
      id: f.id,
      name: f.name,
      url: f.url || '',
      fullUrl: getFileUrl(f.url),
      raw: null
    }));

    uploadRefFileList.value = uploadedFiles.value.map(f => ({
      name: f.name,
      url: f.fullUrl,
      status: 'success',
      raw: f.raw,
      id: f.id
    }));

    // 更新表单 attachment 字段
    form.value.attachmentId = uploadedFiles.value.map(f => f.id).join(',');
    form.value.attachmentName = uploadedFiles.value.map(f => f.name).join(',');

  } catch (err) {
    console.error('附件加载失败', err);
    ElMessage.error('附件加载失败');
  }
};


// 取消上传
const cancelUpload = () => {
  upload.open = false;
  uploadRefFileList.value = [];
  uploadRef.value?.clearFiles();
};

// 获取完整 URL
const getFileUrl = (url: string) => {
  if (!url) return '';
  // 已经是完整路径就直接返回
  if (url.startsWith('http') || url.startsWith('file://')) return url;
  // 去掉前面的 '/upload'，然后拼接
  const fileName = url.substring(url.lastIndexOf('/') + 1); 
  return `${BASE_URL}upload/${fileName}`;
};

/**
 * 删除单个文件
 * @param file 当前删除的文件对象
 * @param index 文件在 file-list 中的索引
 */
const handleFileRemove = async (file: any, fileList: any[]) => {
  console.log("准备删除的文件:", file, fileList);
  try {
    if (file.id) {
      await deleteUploadFile(file.id);
    }
    ElMessage.success(`${file.name} 已删除`);
    // 删除后刷新附件列表
    await loadAttachments();
  } catch (err) {
    console.error('删除文件失败', err);
    ElMessage.error(`删除文件 ${file.name} 失败`);
  }
};

/**
 * 文件预览
 * @param row 
 */
const handlePreview = (row: any) => {
  const ext = row.name?.split(".").pop()?.toLowerCase();
  let type = "";
  if (["jpg", "jpeg", "png", "gif"].includes(ext)) type = "image";
  else if (ext === "pdf") type = "pdf";
  else if (ext === "doc") {
    ElMessage.warning("暂不支持旧版 .doc 格式，请转成 .docx");
    return;
  } else if (ext === "docx") type = "word";
  else if (["xls", "xlsx"].includes(ext)) type = "excel";
  else type = "other";
  // 如果是本地文件，row.raw 必须是真 File 对象
  const rawFile = row.raw instanceof File ? row.raw : null;
  const url = row.url || (rawFile ? URL.createObjectURL(rawFile) : "");
  preview.open = true;
  preview.url = url;
  preview.title = row.name;
  preview.type = type;
  preview.rawFile = rawFile; // 传给 FilePreview
};

/**
 * 初始化或获取表单关联的 number
 * @param form - 表单对象
 * @param isNew - 是否是新增表单
 */
const initOrAssignNumber = (form: MobilityForm, isNew: boolean) => {
  if (isNew) {
    // 新增场景：如果 number 为空，生成新的 UUID
    if (!form.number) {
      form.number = generateUUID32()
    }
  } else {
    // 修改场景：保证 number 已存在，否则抛错提示
    if (!form.number) {
      throw new Error('修改表单时 number 不存在，无法保持关联！')
    }
    // 不做生成，直接使用已有 number
  }
  return form.number
}

/**
 * 生成32位UUID
 * @returns string 32位UUID
 */
function generateUUID32(): string {
  // 生成标准 UUID v4，然后去掉 "-"
  return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, () =>
    ((Math.random() * 16) | 0).toString(16)
  );
}

// 部门选择处理（安全版）
const handleDeptChange = (selectedId: string | number) => {
  console.log('[handleDeptChange] 选中部门 ID:', selectedId);
  const selectedNode = findNodeById(deptTree.value, selectedId);
  if (!selectedNode) return;

  console.log('[handleDeptChange] 选中部门名称:', selectedNode.label);

  if (requiredProjectDepts.includes(selectedNode.label)) {
    console.log('[handleDeptChange] 部门在必填列表，触发项目搜索');
    searchProjects(selectedNode.label, true); // 传 true
  } else {
    console.log('[handleDeptChange] 部门不在必填列表，清空项目选择');
    form.value.projectIdArray = []; // 清空多选回显
    projectList.value = [];         // 可选：清空下拉列表
  }
};

// 遍历树查找节点
function findNodeById(tree: any[], id: string | number): any {
  for (const node of tree) {
    if (node.id === id) return node;
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) return found;
    }
  }
  return null;
}

/** 远程搜索项目 */
const searchProjects = (query: string, isDeptTrigger = false) => {
  projectSearchKeyword.value = query;
  if (projectSearchTimer) clearTimeout(projectSearchTimer);

  projectSearchTimer = setTimeout(() => {
    getProjectList(query || '', isDeptTrigger);
  }, 300);
};

// 获取项目列表
const getProjectList = async (searchKeyword = '', isDeptTrigger = false) => {
  try {
    projectLoading.value = true;
    const requestId = ++currentRequestId;

    const res = await pageListForQuery({
      pageNum: 1,
      pageSize: 50,
      flowStatus: '3',
      proName: searchKeyword || undefined
    });

    if (requestId !== currentRequestId) return; // 避免旧请求覆盖

    projectList.value = res.rows || [];
    console.log('[getProjectList] 接口返回项目列表数量:', projectList.value.length);

    if (isDeptTrigger) {
      // 部门触发搜索 → 全部项目 ID 回显
      form.value.projectIdArray = projectList.value.map(p => String(p.id));
      console.log('[回显] 部门触发 projectIdArray:', form.value.projectIdArray);
    } else if (!backfillDone.value && form.value.projectIdArray?.length) {
      // 回显逻辑：检查本地是否匹配全部 ID
      const missingIds = form.value.projectIdArray.filter(
        id => !projectList.value.some(p => String(p.id) === id)
      );

      if (missingIds.length > 0) {
        console.log('[getProjectList] 有缺失项目，需要调用搜索补全:', missingIds);
        backfillDone.value = true; // 标记已经补全，避免循环

        // 调用远程接口补全
        const projectPromises = missingIds.map(id => getProInfo(Number(id)));
        const projectData = await Promise.all(projectPromises);

        // 将补全的数据加入项目列表并更新回显
        projectData.forEach(res => {
          if (res?.data) {
            projectList.value.push({
              id: res.data.id,
              proName: res.data.proName,
              proNumber: res.data.proNumber,
              contractId: 0,
              contractName: '',
              projectRegion: '',
              proType: '',
              proContent: '',
              proPresidentsId: '',
              proLeadersId: '',
              ownerUnit: '',
              proAmount:  null,
              proAmountRemark: '',
              proStatus: '',
              remark: '',
              createTime: '',
              createBy: ''
            });
          }
        });

        // 确保回显
        form.value.projectIdArray = [...form.value.projectIdArray];
        console.log('[getProjectList] 补全完成，停止回显循环');
      } else {
        console.log('[getProjectList] 本地列表匹配到全部 projectId，回显完成');
        backfillDone.value = true;
      }
    }
  } catch (error) {
    console.error('获取项目列表失败:', error);
    ElMessage.error('获取项目列表失败');
  } finally {
    projectLoading.value = false;
  }
};

/** 处理项目选择变化 */
const handleProjectChange = (value: number | string | undefined) => {
  flowSearchKeyword.value = ''; // 清空流程搜索关键词

  // 项目改变时不清空工作日志列表，允许多个项目的数据共存
};

/** 审核流程确认回调 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('工作日志审核流程提交成功');
    approvalFlowVisible.value = false;
    currentSubmitAuditRow.value = null;
    auditIdForApproval.value = undefined;
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/** 审核流程取消回调 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentSubmitAuditRow.value = null;
  auditIdForApproval.value = undefined;
  // 审核流程取消时，表单已经在submitCurrentWorklogs中重置了，这里不需要重复重置
};

// 打开审批弹窗
const openApprovalFlow = (row?: MobilityVO) => {
  if (row.status != 5){
    ElMessage.error('只能提交已导入的信息审批！');
    return;
  }
  auditIdForApproval.value = row.id;
  approvalFlowVisible.value = true;
};

onMounted(() => {
  getList();
  fetchDeptTree();
});
</script>
